import { Hono } from 'hono'
import { z } from 'zod'
import { AdminService } from '@/services/adminService'
import { getCurrentUser } from '@/middleware/auth'
import { asyncHandler, ValidationError } from '@/middleware/errorHandler'

// 验证模式
const approvePluginSchema = z.object({
  reason: z.string().optional()
})

const rejectPluginSchema = z.object({
  reason: z.string().min(10).max(500)
})

const suspendPluginSchema = z.object({
  reason: z.string().min(10).max(500)
})

const suspendUserSchema = z.object({
  reason: z.string().min(10).max(500)
})

const paginationSchema = z.object({
  page: z.string().optional().transform(val => val ? parseInt(val, 10) : 1),
  limit: z.string().optional().transform(val => val ? parseInt(val, 10) : 20)
})

const pluginFiltersSchema = z.object({
  status: z.enum(['pending', 'approved', 'rejected', 'suspended']).optional(),
  category: z.string().optional(),
  developerId: z.string().optional(),
  search: z.string().optional()
}).merge(paginationSchema)

const userFiltersSchema = z.object({
  status: z.enum(['active', 'suspended', 'inactive']).optional(),
  role: z.enum(['developer', 'admin']).optional(),
  verified: z.string().optional().transform(val => val === 'true' ? true : val === 'false' ? false : undefined),
  search: z.string().optional()
}).merge(paginationSchema)

const auditLogFiltersSchema = z.object({
  action: z.string().optional(),
  resourceType: z.enum(['plugin', 'user', 'api_key']).optional(),
  userId: z.string().optional(),
  startDate: z.string().optional().transform(val => val ? new Date(val) : undefined),
  endDate: z.string().optional().transform(val => val ? new Date(val) : undefined)
}).merge(paginationSchema)

// 验证中间件
const validateQuery = (schema: z.ZodSchema) => {
  return async (c: any, next: any) => {
    try {
      const query = c.req.query()
      const validatedData = schema.parse(query)
      c.set('validatedQuery', validatedData)
      await next()
    } catch (error) {
      if (error instanceof z.ZodError) {
        throw new ValidationError(`Invalid query parameters: ${error.errors.map(e => e.message).join(', ')}`)
      }
      throw error
    }
  }
}

const validateJson = (schema: z.ZodSchema) => {
  return async (c: any, next: any) => {
    try {
      const body = await c.req.json()
      const validatedData = schema.parse(body)
      c.set('validatedData', validatedData)
      await next()
    } catch (error) {
      if (error instanceof z.ZodError) {
        throw new ValidationError(`Invalid request body: ${error.errors.map(e => e.message).join(', ')}`)
      }
      throw error
    }
  }
}

const admin = new Hono()
const adminService = new AdminService()

// 获取当前管理员ID的辅助函数
const getCurrentAdminId = (c: any): string => {
  const user = getCurrentUser(c)
  if (!user) {
    throw new Error('User not authenticated')
  }
  return user.sub
}

// ============ 插件管理 ============

// 获取待审核插件列表
admin.get('/plugins/pending',
  validateQuery(pluginFiltersSchema),
  asyncHandler(async (c) => {
    const filters = c.get('validatedQuery')
    const result = await adminService.getPendingPlugins(filters.page, filters.limit)

    return c.json({
      success: true,
      data: result,
      message: 'Pending plugins retrieved successfully'
    })
  })
)

// 获取所有插件（管理员视图）
admin.get('/plugins',
  validateQuery(pluginFiltersSchema),
  asyncHandler(async (c) => {
    const filters = c.get('validatedQuery')
    // 这里可以调用插件服务的管理员视图方法
    // 暂时返回待审核插件
    const result = await adminService.getPendingPlugins(filters.page, filters.limit)

    return c.json({
      success: true,
      data: result,
      message: 'Plugins retrieved successfully'
    })
  })
)

// 审核通过插件
admin.put('/plugins/:id/approve',
  validateJson(approvePluginSchema),
  asyncHandler(async (c) => {
    const adminId = getCurrentAdminId(c)
    const pluginId = c.req.param('id')
    const data = c.get('validatedData')

    await adminService.approvePlugin(adminId, pluginId, data.reason)

    return c.json({
      success: true,
      message: 'Plugin approved successfully'
    })
  })
)

// 拒绝插件
admin.put('/plugins/:id/reject',
  validateJson(rejectPluginSchema),
  asyncHandler(async (c) => {
    const adminId = getCurrentAdminId(c)
    const pluginId = c.req.param('id')
    const data = c.get('validatedData')

    await adminService.rejectPlugin(adminId, pluginId, data.reason)

    return c.json({
      success: true,
      message: 'Plugin rejected successfully'
    })
  })
)

// 暂停插件
admin.put('/plugins/:id/suspend',
  validateJson(suspendPluginSchema),
  asyncHandler(async (c) => {
    const adminId = getCurrentAdminId(c)
    const pluginId = c.req.param('id')
    const data = c.get('validatedData')

    await adminService.suspendPlugin(adminId, pluginId, data.reason)

    return c.json({
      success: true,
      message: 'Plugin suspended successfully'
    })
  })
)

// 恢复插件
admin.put('/plugins/:id/restore',
  asyncHandler(async (c) => {
    const adminId = getCurrentAdminId(c)
    const pluginId = c.req.param('id')

    await adminService.restorePlugin(adminId, pluginId)

    return c.json({
      success: true,
      message: 'Plugin restored successfully'
    })
  })
)

// ============ 用户管理 ============

// 获取用户列表
admin.get('/users',
  validateQuery(userFiltersSchema),
  asyncHandler(async (c) => {
    const filters = c.get('validatedQuery')
    const result = await adminService.getUsers(
      filters.page,
      filters.limit,
      {
        status: filters.status,
        role: filters.role,
        verified: filters.verified,
        search: filters.search
      }
    )

    return c.json({
      success: true,
      data: result,
      message: 'Users retrieved successfully'
    })
  })
)

// 暂停用户
admin.put('/users/:id/suspend',
  validateJson(suspendUserSchema),
  asyncHandler(async (c) => {
    const adminId = getCurrentAdminId(c)
    const userId = c.req.param('id')
    const data = c.get('validatedData')

    await adminService.suspendUser(adminId, userId, data.reason)

    return c.json({
      success: true,
      message: 'User suspended successfully'
    })
  })
)

// 恢复用户
admin.put('/users/:id/restore',
  asyncHandler(async (c) => {
    const adminId = getCurrentAdminId(c)
    const userId = c.req.param('id')

    await adminService.restoreUser(adminId, userId)

    return c.json({
      success: true,
      message: 'User restored successfully'
    })
  })
)

// ============ 系统统计 ============

// 获取系统统计
admin.get('/stats',
  asyncHandler(async (c) => {
    const stats = await adminService.getSystemStats()

    return c.json({
      success: true,
      data: stats,
      message: 'System statistics retrieved successfully'
    })
  })
)

// ============ 审计日志 ============

// 获取审计日志
admin.get('/audit-logs',
  validateQuery(auditLogFiltersSchema),
  asyncHandler(async (c) => {
    const filters = c.get('validatedQuery')
    const result = await adminService.getAuditLogs(
      filters.page,
      filters.limit,
      {
        action: filters.action,
        resourceType: filters.resourceType,
        userId: filters.userId,
        startDate: filters.startDate,
        endDate: filters.endDate
      }
    )

    return c.json({
      success: true,
      data: result,
      message: 'Audit logs retrieved successfully'
    })
  })
)

export default admin
